package com.handibigdata.base.web;


import com.google.common.collect.ImmutableMap;
import com.handibigdata.base.enums.HqdErrorCode;
import com.handibigdata.haf.common.config.HafContext;
import com.handibigdata.haf.common.exception.HafI18NException;
import com.handibigdata.haf.common.security.GuestApi;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by weihan on 2016/10/9.
 */

@RestController
@RequestMapping("/${version}/config")
public class ConfigController {

    private static final String MODULE_HOST_PRE = "module.host.";

    @GuestApi
    @RequestMapping(path = "/module/host/{module_name}", method = RequestMethod.GET)
    public Map getModuleHost(@PathVariable("module_name") String module,
                             HttpServletRequest request) {
        String moduleHost = HafContext.getProperty(MODULE_HOST_PRE.concat(module));
        if (StringUtils.isEmpty(moduleHost)) {
            throw HafI18NException.of(HqdErrorCode.MODULE_NOT_FOUND);
        }
        String host = request.getScheme().concat("://").concat(request.getServerName());
        return ImmutableMap.of("host", moduleHost.replaceAll("\\{host\\}", host));
    }
}